#include "rendermanager.h"
#include "../datamanager/geometrydatanode.h"
#include "../datamanager/reg3volumedatanode.h"
#include "../datamanager/proteindatanode.h"

using namespace PBVP;

RenderManager::RenderManager()
{
	m_pEnv = new Environment();
}

RenderManager::~RenderManager()
{
	delete m_pEnv;
	RenderPlugin* pRender;

	while (m_RendererList.size() > 0)
	{
		pRender = m_RendererList.last();
		m_RendererList.pop_back();
		pRender->unload();
		delete pRender;
	}
}

void RenderManager::addRenderPlugin(RenderPlugin* pRender)
{
	m_RendererList.append(pRender);
}

bool RenderManager::makeRendererCurrent(RenderPlugin* pRender)
{
	m_pCurrentRenderer = pRender;
	return true;
}

void RenderManager::getGeometryRenderPlugins(QList<GeometryRenderPlugin *>& geoRenderList) const
{
	RenderPlugin *pRender;
	GeometryRenderPlugin *pGeoRender;
	for(int i = 0; i < m_RendererList.size(); i++) {
		pRender = m_RendererList[i];
		pGeoRender = dynamic_cast<GeometryRenderPlugin *>(pRender);
		if (pGeoRender)
		{
			geoRenderList.append(pGeoRender);
		}
	}
}

void RenderManager::getVolumeRenderPlugins(QList<VolumeRenderPlugin *>& volRenderList) const
{
	RenderPlugin *pRender;
	VolumeRenderPlugin *pVolRender;
	for(int i = 0; i < m_RendererList.size(); i++) {
		pRender = m_RendererList[i];
		pVolRender = dynamic_cast<VolumeRenderPlugin *>(pRender);
		if (pVolRender)
		{
			volRenderList.append(pVolRender);
		}
	}
}

void RenderManager::getProteinRenderPlugins(QList<ProteinRenderPlugin*> &proRenderList) const
{
	RenderPlugin *pRender;
	ProteinRenderPlugin *pProRender;
	for(int i = 0; i < m_RendererList.size(); i++) {
		pRender = m_RendererList[i];
		pProRender = dynamic_cast<ProteinRenderPlugin *>(pRender);
		if(pProRender) {
			proRenderList.append(pProRender);
		}
	}
}

QList<RenderPlugin *> RenderManager::getSupportedPlugins(DataInterface *pData) const
{
	QList<RenderPlugin *> renderList;
	RenderPlugin *pRender;
	for(int i = 0; i < m_RendererList.size(); i++) {
		pRender = m_RendererList[i];
		if(pRender->isSupported(pData)) {
			renderList.append(pRender);
		}
	}
	return renderList;
}

void RenderManager::setDefaultRenderer(DataNode *pNode)
{
	DataInterface *pData = pNode->data();
	QList<RenderPlugin *> renderList = getSupportedPlugins(pData);
	if(renderList.size() > 0) {
		// use the first renderer in the list
		pNode->setRenderer(renderList[0]->clone());
	}
}
